﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Security.Cryptography;

/// <summary>
///Aes加解密
/// </summary>
public class Aes
{
    public static string AESEnc(string str)  //key必须为16或32位英文数字,加密输出结果为base64串
    {
        string key = "1@#^fdssd345+)8*sd2fs3wd5ss7d4a9";
        if (str == null || str.Length == 0) return "";
        string iv = "a3m(6j7@" + key;
        if (iv.Length > 16) iv = iv.Substring(0, 16);
        byte[] data = Encoding.UTF8.GetBytes(str);
        using (RijndaelManaged aes = new RijndaelManaged())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform ict = aes.CreateEncryptor();
            byte[] jg = ict.TransformFinalBlock(data, 0, data.Length);
            return Convert.ToBase64String(jg);
        }
    }

    public static string AESDec(string base64str)  //key必须为16或32位英文数字,解密输入结果为base64串
    {
        string key = "1@#^fdssd345+)8*sd2fs3wd5ss7d4a9";
        if (base64str == null || base64str.Length == 0) return "";
        string iv = "a3m(6j7@" + key;
        if (iv.Length > 16) iv = iv.Substring(0, 16);
        RijndaelManaged aes = new RijndaelManaged();
        try
        {
            byte[] data = Convert.FromBase64String(base64str);
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform ict = aes.CreateDecryptor();
            byte[] jg = ict.TransformFinalBlock(data, 0, data.Length);
            aes.Dispose();
            return Encoding.UTF8.GetString(jg);
        }
        catch
        {
            aes.Dispose();
            return "";
        }
    }
}